package demo;

import java.util.Arrays;
import java.util.Comparator;

/**
 * Created with IntelliJ IDEA
 * Description:给对象排序
 * User:恋恋
 * Date:2022-09-18
 * Time:23:08
 */
class Student implements Comparable<Student> {
    public String name;
    public  int score;

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }


        @Override
    public int compareTo(Student student) {
        if(this.score>student.score){
            return 1;
        }else if(this.score<student.score){
            return -1;
        }else{
            return 0;
        }
    }


}
class ScoreComparator implements Comparator<Student>{
    @Override
    public int compare(Student student, Student t1) {
        return student.score-t1.score;
    }
}
class NameComparator implements Comparator<Student>{
    @Override
    public int compare(Student student, Student t1) {
        return student.name.compareTo(t1.name);//name是字符串类型的，字符串中也有compareTO方法，直接调用就可以了
    }
}
public class TestDemo {
    public static void sortOne(Comparable[] students){//数组中的每个元素都实现Comparable接口，并且这个对象（students类）重写comparableTO方法
        for (int i = 1; i < students.length; i++) {//趟数=元素个数-1
            for (int j = 0; j <students.length-i ; j++) {//对数=比较的元素个数-1
                if(students[j].compareTo(students[j+1])>0){
                    Comparable tmp=students[j];
                    students[j]=students[j+1];
                    students[j+1]=tmp;
                }
            }
        }
    }

    public static void main(String[] args) {

    }

    public static void main1(String[] args) {
        Student[] students=new Student[]{
                new Student("你好",90),
                new Student("直接",100),
                new Student("再见",98),
                new Student("回见",99),
        };//静态初始化---对象数组
        sortOne(students);
        System.out.println(Arrays.toString(students));
//        ScoreComparator scoreComparator=new ScoreComparator();
//       if(scoreComparator.compare(students[0],students[1])>0){
//           System.out.println("students[0]>students[1]");
//       }else{
//           System.out.println("students[0]<students[1]");
//       }
//        NameComparator nameComparator=new NameComparator();
//        if(nameComparator.compare(students[0],students[1])>0){
//            System.out.println("students[0]>students[1]");
//       }else{
//          System.out.println("students[0]<students[1]");
//       }

//        if(students[0].compareTo(students[1])==1){
//            System.out.println("students[0]>students[1]");
//        }else if(students[0].compareTo(students[1])==-1){
//            System.out.println("student[0]<student[1]");
//        }else{
//            System.out.println("student[0]==student[1]");
//        }
    }
}
